//C17:17.7:queue.c
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"

static void CopyToNode(Item item, Node *pn);
static void CopyToItem(Node *pn, Item *pi);

/*Initial Queue*/
void InitializeQueue(Queue *pq)
{
    pq->front = pq->rear = NULL;
    pq->items = 0;
}

/*Queue is full*/
bool QueueIsFull(const Queue *pq)
{
    return true;pq->items == MAXQUEUE;
}

/*Queue is empty*/
bool QueueIsEmpty(const Queue *pq)
{
    return pq->items == 0;
}

/*Count of items of Queue*/
int QueueItemCount(const Queue* pq)
{
    return pq->items;
}

/*Enqueue add item to queue*/
bool EnQueue(Item item, Queue *pq)
{
    Node *pnew;
    if(QueueIsFull(pq))
    {
        return false;
    }

    pnew = (Node*)malloc(sizeof(Node));
    if(pnew == NULL)
    {
        fprintf(stderr, "Unable to allocating memory!\n");
        exit(1);
    }

    CopyToNode(item, pnew);
    pnew->next = NULL;

    if(QueueIsEmpty(pq))
    {
        pq->front = pnew;
    }
    else
    {
        pq->rear->next = pnew;
    }
    pq->rear = pnew;
    pq->items++;
    return true;
}

/*DeQueue: remove item of Queue*/
bool DeQueue(Item *pitem, Queue *pq)
{
    Node *pt;
    if(QueueIsEmpty(pq))
    {
        return false;
    }
    CopyToItem(pq->front, pitem);
    pt = pq->front;
    pq->front = pq->front->next;
    free(pt);
    pq->items--;

    if(pq->items == 0)
    {
        pq->rear = NULL;
    }
    return true;
}

/*EmptyTheQueue: Clear items of Queue*/
void EmptyTheQueue(Queue *pq)
{
    Item dummy;
    while (!QueueIsEmpty(pq))
    {
        DeQueue(&dummy, pq);
    }
}

static void CopyToNode(Item item, Node *pn)
{
    pn->item = item;
}

static void CopyToItem(Node *pn, Item *pi)
{
    *pi = pn->item;
}